#import "IosWechat.h"
#import "../IosBase/IosDebug.h"
#import "./WXCallback.h"
#import "../IosBase/IosBase.h"
static id<WechatDelegate> gWechatDelegateInst;
static id<WXApiDelegate> gWXCallbackInst;


@implementation IosWechat

+(void)go:(NSString*) wxAppId universalLink:(NSString*) universalLink delegate:(id<WechatDelegate>) delegate
{
    gWechatDelegateInst = delegate;
    
    gWXCallbackInst = [[WXCallback alloc] init:delegate];
    [gWXCallbackInst retain];
    
    //在register之前打开log, 后续可以根据log排查问题
    if([IosDebug Enable])
    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
        NSLog(@"WeChatSDK: %@", log);
    }];
    
    //向微信注册
    [WXApi registerApp:wxAppId universalLink:universalLink];
    
    //调用自检函数
    if([IosDebug Enable])
    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult* result) {
        NSLog(@"WeChatSDK step: %@, s:%u, e:%@, su:%@", @(step), result.success, result.errorInfo, result.suggestion);
    }];
}

+(BOOL)override_application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:gWXCallbackInst];
}

+(BOOL)override_application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:gWXCallbackInst];
}


+(BOOL)override_application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler {
    return [WXApi handleOpenUniversalLink:userActivity delegate:gWXCallbackInst];
}

+(void)override_scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity {
    [WXApi handleOpenUniversalLink:userActivity delegate:gWXCallbackInst];
}

+(NSString*) gen_uuid
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    CFRelease(uuid_ref);
    NSString *uuid = [NSString stringWithString:(NSString*)uuid_string_ref];
    CFRelease(uuid_string_ref);
    return uuid;
}

+(void)sendAuthRequest
{
    if([WXApi isWXAppInstalled])
    {
        SendAuthReq* req =[[[SendAuthReq alloc]init]autorelease];
        req.scope = @"snsapi_userinfo";
        
        if(WXReqState!=nil) [WXReqState release];
        WXReqState = [self gen_uuid];
        [WXReqState retain];
        
        req.state = WXReqState;
      
        
        
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendAuthReq:req viewController:[IosBase getRootView] delegate:gWXCallbackInst completion:nullptr ];
    } else
        [gWechatDelegateInst onLoginFail:1];//没有安装微信
}

@end
